<?php

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require(ROOT_PATH . 'includes/lib_order.php');
require(ROOT_PATH . 'plugins/kdniao/kdniao_config.php');

$data = $_POST;
$log = '【'.date('Y-m-d H:i:s').'】'.var_export($_POST,true).PHP_EOL;
file_put_contents(ROOT_PATH.'log/kdapi.txt', $log,FILE_APPEND | LOCK_EX);

$result = array('EBusinessID'=>EBusinessID,'UpdateTime'=>local_date('Y-m-d H:i:s'),'Success'=>false);
if ($data['RequestType'] != '101'){
	$result['Reason'] = 'RequestType错误';
	die(json_encode($result));
}

// $requestData = urldecode($data['RequestData']);
$requestData = $data['RequestData'];
$requestData = stripslashes($requestData);

if (base64_encode(md5($requestData.AppKey)) != $data['DataSign']){
	$result['Reason'] = '签名错误';
	die(json_encode($result));
}

$data['RequestData'] = json_decode($requestData,true);
$orders = $data['RequestData']['Data'];
if (is_array($orders)){
	foreach ($orders as $k=>$v){
		$invoice_no = $v['LogisticCode'];
		$state = $v['State'];
		$order = get_order_by_invoice_no($invoice_no);
		if ($order){
			$ship_status = $order['shipping_status'];
			switch ($state){
				case 0:
					break;
				case 1:
					break;
				case 2:
					break;
				case 201://正在派件
					if (!in_array($ship_status,array(SS_ROAD,SS_SIGN,SS_RECEIVED))){
						update_order($order['order_id'], array('shipping_status'=>SS_ROAD));
						order_action($order['order_sn'], $order['order_status'], SS_ROAD, $order['pay_status'], '', '快递鸟推送接口');
					}
					break;
				case 3://签收
					if (!in_array($ship_status,array(SS_SIGN,SS_RECEIVED))){
						update_order($order['order_id'], array('shipping_status'=>SS_SIGN,'sign_time'=>gmtime()));
						order_action($order['order_sn'], $order['order_status'], SS_SIGN, $order['pay_status'], '', '快递鸟推送接口');
					}
					break;
				case 4:
					break;
			}
		}
	
	}
}


$result['Success'] = true;
echo json_encode($result);

/**
 * 电商Sign签名生成
 * @param data 内容
 * @param appkey Appkey
 * @return DataSign签名
 */
function kd_encrypt($data, $appkey) {
	return urlencode(base64_encode(md5($data.$appkey)));
}

?>